module.exports = function(sequelize, DataTypes) {
  var Material = sequelize.define(
    'Material',
    {
      type: {
        type: DataTypes.ENUM('audio', 'image'),
        comments: '类型'
      },
      userId: {
        type: DataTypes.INTEGER
      },
      key: {
        type: DataTypes.STRING(50)
      },
      size: {
        type: DataTypes.INTEGER
      },
      meta: {
        type: DataTypes.TEXT,
        allowNull: false,
        get() {
          let meta = this.getDataValue('meta')
          if (!meta) return {}
          return JSON.parse(meta)
        },
        set(val) {
          this.setDataValue('meta', JSON.stringify(val))
        }
      }
    },
    {
      tableName: 'materials',
      paranoid: true,
      indexes: [
        {
          name: 'key_idx',
          fields: ['key']
        },
        {
          name: 'user_id_idx',
          fields: ['userId']
        }
      ],
      comments: '资源信息表'
    }
  )

  Material.associate = function(models) {
    this.belongsTo(models.User, {
      as: 'user',
      constraints: false,
      foreignKey: 'userId'
    })
  }

  return Material
}
